package com.zhiqianbao.adapter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zhiqianbao.R;
import com.zhiqianbao.activity.RepayVerifyActivity;
import com.zhiqianbao.entity.Repay;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;

/**
 * 应还款列表
 *
 * Created by liang on 2016/1/13.
 */
public class BeforeRepayListAdapter extends BaseAdapter {
    List<Repay> list;
    private LayoutInflater inflater;
    private Activity ctx;
    private String state = "0";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    public BeforeRepayListAdapter(Activity context, List<Repay> list) {
        this.ctx = context;
        this.list = list;
        this.inflater = LayoutInflater.from(context);
    }
    public BeforeRepayListAdapter(Activity activity, List<Repay> list, String state) {
        this.ctx = activity;
        this.list = list;
        this.inflater = LayoutInflater.from(ctx);
        this.state = state;
    }

    private final class ListItemView {
        //还款额度显示
        TextView textViewMoney;
        //期数
        TextView textviewSeq;
        //逾期状态
        TextView textViewMoneyOrderOverdue;
        //到期日显示
        TextView textViewMoneyOrderReturnMoneyTime;
        //协议号显示
        //TextView textViewMoneyOrderNum;
        //整个item
        RelativeLayout accountListItemBackgroundOkOrNo;

        TextView zero;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ListItemView listItemView = null;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.list_item_moneymessages_02, null);
            listItemView = new ListItemView();
            listItemView.textViewMoney = (TextView) convertView.findViewById(R.id.textView_money);
            listItemView.textviewSeq = (TextView) convertView.findViewById(R.id.textview_seq);
            listItemView.textViewMoneyOrderOverdue = (TextView) convertView.findViewById(R.id.textView_moneyOrder_overdue);
            listItemView.textViewMoneyOrderReturnMoneyTime = (TextView) convertView.findViewById(R.id.textView_moneyOrder_returnMoneyTime);
            //listItemView.textViewMoneyOrderNum = (TextView) convertView.findViewById(R.id.textView_moneyOrder_num);
            listItemView.accountListItemBackgroundOkOrNo = (RelativeLayout) convertView.findViewById(R.id.account_list_item_background_ok_or_no);
            listItemView.zero = (TextView) convertView.findViewById(R.id.zero);
            convertView.setTag(listItemView);
        } else {
            listItemView = (ListItemView) convertView.getTag();
        }

        //已还款状态 显示绿色
        if (Constants.AFTER_REPAYMENT.equals(state)) {
            listItemView.textViewMoneyOrderOverdue.setTextColor(Color.parseColor("#ff61C597"));
            listItemView.zero.setTextColor(Color.parseColor("#ff61C597"));
            listItemView.textViewMoney.setTextColor(Color.parseColor("#ff61C597"));

            listItemView.accountListItemBackgroundOkOrNo.setBackgroundResource(R.drawable.i_img_applying_ok_list_item_background);
        } else {
            listItemView.textViewMoneyOrderOverdue.setTextColor(Color.parseColor("#fffa715c"));
            listItemView.zero.setTextColor(Color.parseColor("#fffa715c"));
            listItemView.textViewMoney.setTextColor(Color.parseColor("#fffa715c"));


            listItemView.accountListItemBackgroundOkOrNo.setBackgroundResource(R.drawable.i_img_applying_no_list_item_background);
        }

        String textViewMoneyStr = list.get(position).getRepayTotal()+"";
        String textviewSeq = list.get(position).getTerms().toString();

        //当前时间大于 到期时间  已逾期
        String textViewMoneyOrderOverdueStr = "";
        if (Constants.AFTER_REPAYMENT.equals(state)) {
            textViewMoneyOrderOverdueStr += "已还款，";
        } else {
            textViewMoneyOrderOverdueStr += "等待还款，";
        }
        Integer overdue = list.get(position).getOverdue();
        overdue = overdue == null ? 0 : overdue;
        if (overdue > 0) {
            textViewMoneyOrderOverdueStr += "已逾期"+ overdue + "天";
        } else {
            textViewMoneyOrderOverdueStr += "未逾期";
        }

        String textViewMoneyOrderReturnMoneyTimeStr = "到期日:" + sdf.format(new Date(list.get(position).getPlayDate()));
        //String textViewMoneyOrderNumStr = "协议号：12345678";
        String zs = textViewMoneyStr.split("\\.")[0];
        String xs = textViewMoneyStr.split("\\.")[1];
        listItemView.textViewMoney.setText(zs);
        listItemView.zero.setText("." + xs);
        listItemView.textviewSeq.setText("第" + textviewSeq + "期");
        listItemView.textViewMoneyOrderOverdue.setText(textViewMoneyOrderOverdueStr);
        listItemView.textViewMoneyOrderReturnMoneyTime.setText(textViewMoneyOrderReturnMoneyTimeStr);
       // listItemView.textViewMoneyOrderNum.setTexbeft(textViewMoneyOrderNumStr);

        //应还款列表 绑定还款
        if (Constants.BEFORE_REPAYMENT.equals(state)) {
            listItemView.accountListItemBackgroundOkOrNo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //每次都取第一个
                    repay = list.get(position);
                    //调用查询是否可以进行还款的接口
                     new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Map<String, String> params = new HashMap<>();
                            params.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                            params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                            params.put("repayId", repay.getId() + "");
                            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/repay/checkPreRepay", params, ctx);
                            Message message = new Message();
                            if (StringUtils.isBlank(result)) {
                                message.what = ctx.RESULT_CANCELED;
                            } else {
                                message.what = ctx.RESULT_OK;
                                Result<String> data = Result.fromJson(result, String.class);
                                message.obj = data;
                            }
                            handler.sendMessage(message);
                        }
                    }).start();

                }
            });
        }
        return convertView;

    }
    Repay repay;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Toast.makeText(ctx, Constants.HTTP_ERROR_MESSAGE, Toast.LENGTH_SHORT).show();
                    break;
                case -1:
                    Result<String> data = (Result<String>) msg.obj;
                    if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                        //不允许还款
                        if (data.getData().equals("0")) {
                            Toast.makeText(ctx, "请等待上一期还款处理完之之后，再进行本期还款。", Toast.LENGTH_SHORT).show();
                            //扣款进行中，请等待扣款结果
                        } else if (data.getData().equals("2")) {
                            Toast.makeText(ctx, "本期已经扣款，请等待处理结果。", Toast.LENGTH_SHORT).show();
                        } else {
                            Intent intent = new Intent(ctx, RepayVerifyActivity.class);
                            intent.putExtra("repay", repay);
                            ctx.startActivity(intent);
                        }
                    } else {
                        Toast.makeText(ctx, data.getMsg(), Toast.LENGTH_SHORT).show();
                    }

                    break;
            }
        }
    };

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
}
